package com.kqzz.common.exception;

import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import cn.hutool.core.codec.Base64;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
	
	public CustomLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }
	
	/**
     * 拼接callbackurl参数到loginPage后
     *
     * @return 重定向到登录页面
     */
    @SneakyThrows
    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        String savedRequestUrl = request.getRequestURL() + "?" + request.getQueryString();
        //这里编码不能使用UrlEncode,会导致参数丢失
        String base64EncodeSavedRequestUrl = Base64.encode(savedRequestUrl, StandardCharsets.UTF_8);
        String redirectUrl = super.getLoginFormUrl() + "?callbackurl=" + base64EncodeSavedRequestUrl;

        log.info("savedRequestUrl:【{}】,redirectUrl:【{}】", savedRequestUrl, super.getLoginFormUrl() + "?callbackurl=" + savedRequestUrl);
        return redirectUrl;
    }
}
